package com.gwtjs.icustom.ioutils;

//import java.io.IOException;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gwtjs.icustom.controller.install.InstallAmbariController;

/**
 * 执行linux shell
 * @author flash
 *
 */
public class ExecuteShell {
	
	private final static Logger logger = LoggerFactory.getLogger(InstallAmbariController.class);
	
	public static String execCmd(String cmd) throws Exception {
		String ret = "";
		String retErr = "";
		long startTime = System.currentTimeMillis();
		
		try {
			Process p = Runtime.getRuntime().exec(new String[] {"/bin/sh", "-c", cmd});
			
			ret = IOUtils.toString(p.getInputStream(), "UTF-8");
			IOUtils.toString(p.getInputStream(), "UTF-8");
			retErr = IOUtils.toString(p.getErrorStream(), "UTF-8");
			
			if (p.waitFor() == 0) {
				if (ret != null) {
					ret = ret.trim();
				}
				
				return ret;
			} else {
				if (retErr!= null) {
					retErr = retErr.trim();
				}
				//throw new IOException("cmd=" + cmd + ", retErr=" + retErr);
				return retErr;
			}
		} catch (Exception e) {
			logger.error("cmd {}\n"+cmd, e);
			
			throw e;
		} finally {
			long finishTime = System.currentTimeMillis();
			long timeUsed = finishTime - startTime;
			
			logger.debug("timeUsed={}, cmd={}", timeUsed, cmd);
			logger.trace("ret={}", ret);
		}
	}
	
}
